//
//  TWAnimationView.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/16.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import SDWebImage

protocol TWAnimationViewDelegate : NSObjectProtocol {
    func animationViewVideoPlayButtonClick(model : TWItemModel)
    func animationViewVideoHalfBottom_ShowMore(itemModel : TWItemModel)                                         // 加载相关内容页面
    func animationViewVideoHalfBottom_Hidden()                                           // 隐藏相关内容页面
    func didmissButtonDidClick()
}

class TWAnimationView: UIView {
    // MARK:- 属性
    var offset : CGFloat?                                              // 传递过来的当前点击的cell的Y轴坐标
//    var seletorIndex : IndexPath?
    
    var videoModelArry : [TWItemModel] = [TWItemModel]()                // 专门存放视频模型的数组
    
    var allArray : [TWItemModel]?{
        didSet {
            guard let allArray = allArray else {
                return
            }
            videoModelArry = allArray
            topCollectionView.videoArray = allArray
        }
    }
    
    var itemModel : TWItemModel?{
        didSet {
            guard let itemModel = itemModel else {
                return
            }
            if itemModel.author == nil {
                halfBottom_authorInfoView.isHidden = true
                lineTopToViewCons.constant = 10
            } else {
                // 有作者信息
                halfBottom_authorInfoView.isHidden = false
                halfBottom_authorInfoIconImageView.sd_setImage(with: URL(string: (itemModel.author?.icon)!))
                halfBottom_authorInfoNameLabel.text = itemModel.author?.name
                halfBottom_authorInfoDetailsLabel.text = itemModel.author?.tw_description
                lineTopToViewCons.constant = 80
            }
            // 设置其他
            halfBottom_TitleLabel.text = itemModel.title
            halfBottom_TimeLabel.text = "#\(itemModel.category!)" + " / " + "\(itemModel.duration_tw!)"
            descriptionEditorLabel.text = itemModel.descriptionEditor
            likeButton.setTitle((itemModel.consumption?.collectionCount)?.stringValue, for: .normal)
            shareButton.setTitle((itemModel.consumption?.shareCount)?.stringValue, for: .normal)
            reviewButton.setTitle((itemModel.consumption?.replyCount)?.stringValue, for: .normal)
            
            // 填充backgroundImageView
            halfBottom_bgImageView.sd_setImage(with:  URL(string: (itemModel.cover?.blurred)!))
            
            // 填充占位图片
            let urlStr = itemModel.cover?.detail
            // 检查图片是否已经被缓存
            let image = SDImageCache.shared().imageFromMemoryCache(forKey: urlStr)
            guard let image1 = image else {
                return
            }
            coverImageView.image = image1
        
            // 传到下层
            topCollectionView.item = itemModel
            
        }
    }
    
    var animationViewDelegate : TWAnimationViewDelegate?
    
    var isOpenCorrelation : Bool = true                                     // 是否已经打开相关信息页面
    

    // MARK:- 子控件
    fileprivate lazy var coverImageView : UIImageView = UIImageView()       // 自定义蒙层
    @IBOutlet weak var dismissButton: UIButton!
    @IBOutlet weak var bigBackGroundScrollView: UIScrollView!
    // 上部分
    @IBOutlet weak var topCollectionView: TWVideoCollectionView!
    @IBOutlet weak var playButton: UIButton!
    // 整个下半部分
    @IBOutlet weak var halfBottomView: UIView!
    // 下半部分视图中顶部的约束
    @IBOutlet weak var halfBottomViewTopCons: NSLayoutConstraint!
    // 下半部分中背景大图
    @IBOutlet weak var halfBottom_bgImageView: UIImageView!
    // 下半部分中最上面一块
    @IBOutlet weak var FirstView: UIView!
    @IBOutlet weak var halfBottom_TitleLabel: UILabel!
    @IBOutlet weak var halfBottom_TimeLabel: UILabel!
    @IBOutlet weak var halfBottom_ShowMoreButton: UIButton!
    
    // 分割线距离时间label的约束
    @IBOutlet weak var lineTopToViewCons: NSLayoutConstraint!
    @IBOutlet weak var lineView: UIView!
    
    // 下半部分中作者信息的视图（可选）
    @IBOutlet weak var halfBottom_authorInfoView: UIView!
    @IBOutlet weak var halfBottom_authorInfoIconImageView: UIImageView!
    @IBOutlet weak var halfBottom_authorInfoNameLabel: UILabel!
    @IBOutlet weak var halfBottom_authorInfoAttentionButton: UIButton!
    @IBOutlet weak var halfBottom_authorInfoDetailsLabel: UILabel!
    // 详细描述
    @IBOutlet weak var descriptionEditorLabel: UILabel!
    // 工具条
    @IBOutlet weak var toolView: UIView!
    @IBOutlet weak var likeButton: UIButton!
    @IBOutlet weak var shareButton: UIButton!
    @IBOutlet weak var reviewButton: UIButton!
    @IBOutlet weak var downloadButton: UIButton!
    
    // MARK:- 监听点击
    @IBAction func didmissButtonClick() {
        animationViewDelegate?.didmissButtonDidClick()
        hiddenAnimationView()
    }
    @IBAction func videoPlayButtonClick() {
        animationViewDelegate?.animationViewVideoPlayButtonClick(model: itemModel!)
    }
    @IBAction func halfBottom_ShowMoreButtonClick() {
        if isOpenCorrelation {
            halfBottomViewTopCons.constant = -UIScreen.main.bounds.width
            self.toolView.alpha = 0
            halfBottom_authorInfoView.alpha = 0
            UIView.animate(withDuration: 0.5) {
                self.halfBottom_ShowMoreButton.imageView?.transform = CGAffineTransform.identity
                self.isOpenCorrelation = false
                // 移动View弹出视图
                self.animationViewDelegate?.animationViewVideoHalfBottom_ShowMore(itemModel: self.itemModel!)
                self.layoutIfNeeded()
                self.lineView.alpha = 0
                self.halfBottom_TimeLabel.alpha = 0
                self.descriptionEditorLabel.alpha = 0
            }
        } else {
            halfBottomViewTopCons.constant = 0
            UIView.animate(withDuration: 0.5) {
                self.halfBottom_ShowMoreButton.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                self.isOpenCorrelation = true
                // 移动View关闭视图
                self.animationViewDelegate?.animationViewVideoHalfBottom_Hidden()
                self.layoutIfNeeded()
                self.halfBottom_TimeLabel.alpha = 1
                self.halfBottom_authorInfoView.alpha = 1
                self.toolView.alpha = 1
                self.lineView.alpha = 1
                self.descriptionEditorLabel.alpha = 1
            }
        }
    }
    
//    static let shareInstens : TWAnimationView = {
//        let animationView = Bundle.main.loadNibNamed("TWAnimationView", owner: nil, options: nil)!.first as! TWAnimationView
//        return animationView
//    }()
    
    // MARK:- 初始化 从xib中加载
    class func createAnimationView() -> TWAnimationView {
        return Bundle.main.loadNibNamed("TWAnimationView", owner: nil, options: nil)!.first as! TWAnimationView
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        setupTopCollectionView()
        setupCoverImageView()
        // 默认按钮是旋转过来的样子
        halfBottom_ShowMoreButton.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
        // 添加边框
        halfBottom_authorInfoAttentionButton.layer.masksToBounds = true
        halfBottom_authorInfoAttentionButton.layer.cornerRadius = 4
        halfBottom_authorInfoAttentionButton.layer.borderWidth = 1
        halfBottom_authorInfoAttentionButton.layer.borderColor = UIColor.white.cgColor
    }
}

// MARK:- ——————设置UI——————
extension TWAnimationView {
    fileprivate func setupCoverImageView() {
        coverImageView.contentMode = .scaleAspectFill
        coverImageView.clipsToBounds = true
        addSubview(coverImageView)
        bringSubview(toFront: coverImageView)
    }
    fileprivate func setupTopCollectionView() {
        let layout = topCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        topCollectionView.isPagingEnabled = true
        topCollectionView.showsVerticalScrollIndicator = false
        topCollectionView.showsHorizontalScrollIndicator = false
        topCollectionView.delegate = self
        topCollectionView.dataSource = self
        topCollectionView.register(UINib(nibName: "TWVideoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: videoCollectionViewCellId)
    }
}

/// 弹出和消失动画
extension TWAnimationView {
    func showAnimationView() {
        self.playButton.alpha = 0
        self.dismissButton.alpha = 0
        self.topCollectionView.alpha = 0
        self.topCollectionView.frame = CGRect(x: 0, y: self.offset! + VideoCellHeight, width: UIScreen.main.bounds.width, height: 0)
        self.coverImageView.alpha = 1
        self.coverImageView.frame = CGRect(x: 0, y: self.offset!, width: UIScreen.main.bounds.width, height: VideoCellHeight)
        self.halfBottomView.frame = CGRect(x: 0, y: self.offset!, width: UIScreen.main.bounds.width, height: 0)
        
        UIView.animate(withDuration: showTime, animations: {
            self.topCollectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
            self.halfBottomView.frame = CGRect(x: 0, y: UIScreen.main.bounds.width, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - UIScreen.main.bounds.width)
            self.coverImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
        }) { (_) in
            self.coverImageView.alpha = 0
            self.topCollectionView.alpha = 1
            self.playButton.alpha = 1
            self.dismissButton.alpha = 1
        }
    }
    
    func hiddenAnimationView() {
        self.coverImageView.alpha = 1
        self.topCollectionView.alpha = 0
        self.halfBottomView.frame = CGRect(x: 0, y: UIScreen.main.bounds.width, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - UIScreen.main.bounds.width)
        self.coverImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
        UIView.animate(withDuration: showTime, animations: {
            self.coverImageView.frame = CGRect(x: 0, y: self.offset!, width: UIScreen.main.bounds.width, height: VideoCellHeight)
            self.halfBottomView.frame = CGRect(x: 0, y: self.offset!, width: UIScreen.main.bounds.width, height: 0)
        }, completion: { (_) in
            self.removeFromSuperview()
        })
    }
}


// MARK:- ——————代理方法——————
// MARK:- collectionView的代理
extension TWAnimationView : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return videoModelArry.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoCollectionViewCellId, for: indexPath) as! TWVideoCollectionViewCell
        cell.cellModel = videoModelArry[indexPath.row]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        videoPlayButtonClick()
    }
}

// MARK:- scrollView的代理
extension TWAnimationView {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 判断是向左还是向右
        let currentPage = Int(topCollectionView.contentOffset.x / UIScreen.main.bounds.width)
        let currentPageFloat = CGFloat(currentPage)
        let alphaValue = (topCollectionView.contentOffset.x / UIScreen.main.bounds.width) - currentPageFloat
        let value : CGFloat = 1 - alphaValue
        halfBottom_authorInfoView.alpha = value
        FirstView.alpha = value
        lineView.alpha = value
        toolView.alpha = value
        descriptionEditorLabel.alpha = value
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 滚动结束后停在第几页(自0开始)
        let pageIndex = Int(topCollectionView.contentOffset.x / UIScreen.main.bounds.width)
        showViewItem(index: pageIndex)
    }
}

// MARK:- 自定义方法
extension TWAnimationView {
    fileprivate func showViewItem(index : Int){
        // 重新设置数据源
        let currentModel = allArray?[index]
        itemModel = currentModel
        let indexPath : IndexPath = IndexPath.init(row: index, section: 0)
        topCollectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        // 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue :AnimationViewScrollCurrentNote), object: currentModel)
    }
}


